package com.lambkit.plugin.activerecord.datasource;

import com.jfinal.kit.LogKit;
import com.lambkit.db.DataSourcePlugin;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

public class DataSourceShardingPlugin extends DataSourcePlugin {
	
	//private static Log log = Log.getLog(DataSourceShardingPlugin.class);

	private final List<DataSourcePlugin> pluginList = new ArrayList<DataSourcePlugin>();
	private DataSource shardingDataSource;

	public DataSourceShardingPlugin(String configName) {
		super(configName);
	}

	@Override
	public boolean start() {
		if (pluginList == null) {
			return true;
		}

		for (DataSourcePlugin plugin : pluginList) {
			if (plugin.start() == false) {
				String message = "Plugin start error: " + plugin.getClass().getName();
				throw new RuntimeException(message);
			}
		}
		return startArp();
	}

	@Override
	public boolean stop() {
		
		stopArp();
		if (pluginList != null) {
			for (int i = pluginList.size() - 1; i >= 0; i--) { // stop plugins
				boolean success = false;
				try {
					success = pluginList.get(i).stop();
				} catch (Exception e) {
					success = false;
					LogKit.error(e.getMessage(), e);
				}
				if (!success) {
					System.err.println("Plugin stop error: " + pluginList.get(i).getClass().getName());
				}
			}
		}
		return true;
	}

	@Override
	public int getDataSourceActiveState() {
		if(shardingDataSource!=null && getArp()!=null) {
			return 0;
		}
		return 1;
	}

	public void monitorDataSourceActive() {
		//未实现
	}

	@Override
	public DataSource getDataSource() {
		
		return shardingDataSource;
	}

	public DataSourceShardingPlugin add(DataSourcePlugin plugin) {
		if (plugin == null) {
			throw new IllegalArgumentException("plugin can not be null");
		}
		pluginList.add(plugin);
		return this;
	}

	public void setShardingDataSource(DataSource shardingDataSource) {
		this.shardingDataSource = shardingDataSource;
	}

	public List<DataSourcePlugin> getPluginList() {
		return pluginList;
	}

}
